package cn.gemiman.daoyi.module.netty.server.mqtt;

import cn.gemiman.daoyi.module.netty.server.NettyServer;
import cn.gemiman.daoyi.module.netty.server.mqtt.options.IMqttMessageListener;
import cn.gemiman.daoyi.module.netty.server.mqtt.options.IMqttVerifyListener;
import cn.gemiman.daoyi.module.netty.server.mqtt.options.MqttServerService;
import io.netty.channel.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * TCP服务器,用于连接非网页的客户端,协议格式： 4字节内容的长度+IMSendInfo的JSON序列化
 *
 * @author Gemiman
 * @date 2022-11-20
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "netty.mqtt", value = "enable", havingValue = "true", matchIfMissing = true)
public class MqttServer implements NettyServer {

    private volatile boolean ready = false;

    @Resource
    private IMqttMessageListener listener;
    @Resource
    private IMqttVerifyListener verifyListener;

    @Value("${netty.mqtt.port}")
    private int port;

    private MqttServerService mqttServer;

    @Override
    public boolean isReady() {
        return ready;
    }

    @Override
    public void start() {
        mqttServer = new MqttServerService();
        //1)简单启动服务，其中60001是监听的端口，listner是实现 `interface IMqttMessageListener`接口的对象，后面会提到
        Channel channel = mqttServer.startup(port, listener, verifyListener);
        if (null != channel) {
            ready = true;
            log.info("Mqtt server 初始化完成,端口：: {}", port);
        } else {
            log.error("Mqtt server 初始化失败,端口: {}", port);
        }
    }

    @Override
    public void stop() {
        if (null != mqttServer) {
            mqttServer.close();
            ready = false;
            mqttServer = null;
        }
    }
}
